import { defineStore } from "pinia";
import { login } from "@/api/user";
import { showNotify } from "vant";
import router from "@/router";
import { NO } from "@vue/shared";

export const useUseStore = defineStore("user", {
  persist: {
    paths: ["token", "userid"],
  },

  state() {
    return {
      username: "15200299384", //用户名
      password: "12345", //密码

      token: "", //登录成功后的token
      userid: "", //用户Id
      loading: false, //为false表示可以请求,为true表示接口在请求中，无法请求
    };
  },

  getters: {
    // 控制登录页面的登录按钮
    isDisabled(state) {
      return !state.username || !state.password;
    },
    // 是否登录
    isLogined(state) {
      return state.token;
    },
  },

  actions: {
    /**
     * 登录
     * @param route 当前匹配的路由信息对象 $route
     */
    async submit(route: any) {
      //设置loading 为true 表示接口正在请求
      this.loading = true;
      //调用接口
      login(this.username, this.password).then((response) => {
        // 登录成功
        //   console.log(response.data)
        // 设置loading为false 表示接口请求完成
        this.loading = false;
        this.token = response.data.token;
        this.userid = response.data.userid;
        showNotify({
          type: "success",
          message: "登录成功",
          duration: 1000,
          onClose: () => {
            // NOtify关闭之后的回调函数
            //跳转到首页
            // router.replace({ name: 'home' })
            //1.获取url中的redirect 参数的值
            // console.log(route.query.redirect)
            const redirect = route.query.redirect || "/home";

            //跳转到原来页面
            router.replace(redirect);
          },
        });
      }
      ).catch(()=>{
        // 设置loading为false 表示接口请求完成
        this.loading=false;
      });
    },

    /**
     * 退出登录
     */
    async logout() {
      //1.清空本地存储
      localStorage.clear();
      //2.清空token与userid
      this.token = "";
      this.userid = "";
      //3.跳转到首页
      router.replace({ name: "home" });
    },
  },
});
